package org.bangumibuddy.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.bangumibuddy.exception.rss.RssSubscribedException;
import org.bangumibuddy.pojo.anime.Anime;
import org.bangumibuddy.pojo.ResponseResult;
import org.bangumibuddy.pojo.TorrentFile;
import org.bangumibuddy.parser.factory.RssParserFactory;
import org.bangumibuddy.service.*;
import org.bangumibuddy.utils.TorrentFilter;
import org.bangumibuddy.vo.SubscribeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@Slf4j
@RequestMapping("/rss")
public class RssController {

    @Autowired
    private RssService rssService;

    @Autowired
    DownloadService downloadService;

    @Autowired
    AnimeService animeService;

    @Autowired
    RssParserService parser;

    @SneakyThrows
    @PostMapping("/analysis")
    public ResponseResult<SubscribeVO> analysisRss(@RequestParam String rss) {
        log.info("订阅地址：{}", rss);
        RssSubscribedCheck(rss);
        SubscribeVO subscribeVO = parser.parseRss(rss);
        return ResponseResult.success(subscribeVO);
    }

    private void RssSubscribedCheck(String rss) {
        if(rssService.isRssSubscribed(rss))
            throw new RssSubscribedException(rss + ",已经订阅过了！");
    }

    @SneakyThrows
    @PostMapping("/subscribe")
    public ResponseResult subscribe(@RequestBody SubscribeVO rss) {
        log.info("订阅地址：{}", rss.getUrl());

        setTorrentFileSelectedByPatterns(rss.getFileList(), rss.getIncludePatterns(), rss.getExcludePatterns());
        List<TorrentFile> torrentFiles = TorrentFilter.filter(rss.getFileList(), rss.getIncludePatterns(), rss.getExcludePatterns());
        if(!downloadService.addDownloadTasks(torrentFiles))
            return ResponseResult.error("添加种子到qb失败！");

        Anime anime = RssParserFactory.create(rss.getUrl()).getAnime();
        //添加数据到数据库
        animeService.addAnime(anime);

        return ResponseResult.success();
    }

    private void setTorrentFileSelectedByPatterns(List<TorrentFile> torrentFiles, List<String> includePatterns, List<String> excludePatterns) {
        for (TorrentFile torrentFile : torrentFiles) {
            boolean isExclude = excludePatterns.isEmpty() ? false : excludePatterns.stream().anyMatch(torrentFile.getTorrentName()::contains);

            boolean isExcludeRegex= excludePatterns.stream().anyMatch(regex->{
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(torrentFile.getTorrentName());

                while (matcher.find()) {
                   return true;
                }
                return false;
            });

            torrentFile.setIsSelected(!(isExclude || isExcludeRegex));
        }
    }
}
